<?php
namespace app\api\controller;

use app\api\model\Splicing;
use app\api\model\Users;
use app\api\model\Order;
use app\api\model\Splicingorder;
use app\api\model\UsersMoneylog;
use app\common\model\Wechatpay;

/**
 * 打印机管理
 *
 * @icon fa fa-circle-o
 */
/**
 * @method array get(string $uri, array $query = [])
 * @method array put(string $uri, array $form_params = [])
 * @method array post(string $uri, array $form_params = [])
 * @method array patch(string $uri, array $form_params = [])
 * @method array delete(string $uri, array $form_params = [])
 */
class Timing extends Api
{
    protected $noNeedLogin = ['*'];
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 基本请求地址
     */
    const BASE_URI = 'https://open.spyun.net/v1/';

    /**
     * 连接超时时间
     */
    const CONNECTTIMEOUT = 1;

    /**
     * 超时时间
     */
    const TIMEOUT = 4;

    /**
     * @var string
     */
    protected $appid="sp669f7f22e5250";

    /**
     * @var $appsecret
     */
    protected $appsecret="81288879aa722dd2367f9b883f0e5830";

    /**
     * @var string
     */
    protected $message;

    /**
     * Dayin模型对象
     * @var \app\admin\model\Dayin
     */
    protected $model = null;

    //查询距离取餐时间十分钟前，未取餐的订单
    public function not_meal_notice(){
        $where['endtime'] = ['<=',time()-600];
        $where['order_status'] = 1;
        $where['is_notice'] = 0;
        $list  = Order::alias("o")
            ->join('users u','u.id=o.users_id')
            ->where($where)
            ->field('o.id,o.order_sn,o.order_status,o.date,o.time,o.endtime,u.phone')
            ->select();
        if(!empty($list)){
            $list = collection($list)->toArray();
            foreach($list as $v){
                if(!empty($v['phone'])){
                    //发送短信通知
                    $res = controller('Sendmsg')->sendSms('融禾汇餐饮管理','SMS_470790025',$v['phone']);
                }
                Order::where(['id'=>$v['id']])->update(['is_notice'=>1]);
            }
        }

    }

    //拼单处理
    public function splicing_timing(){
        $where['endtime'] = ['<=',time()];
//        $where['status'] = ['neq',1];
        $where['status'] = 0;
        $field = "id,num,address,lat,lng,endtime";
        $lists = Splicing::where($where)->field($field)->select();
        $lists = collection($lists)->toArray();
        $dayinji = db("dayin")->where(['status'=>'1'])->find();
        $times = 1;

        foreach($lists as $k=>$v){
            if($v['num'] >= 5){
                Splicing::where(['id'=>$v['id']])->update(['status'=>'1']);
                //发送打印
                $order_list = Splicingorder::where(['splicing_id'=>$v['id'],'order_status'=>'1'])->field("id,order_sn,address,users_id,posts_money,posts_name,name,phone,order_sn,money,bonus_id,pay_type,addtime")->select();
                $order_list = collection($order_list)->toArray();
                foreach($order_list as $key=>$value){
                    $keys = $key+1;
                    $content = "<C><H><B>"."订单号:".$value['order_sn']."</B></H></C>";
                    $content .= "--------------------------------"."<BR>";
                    $content .= "------------".$keys."号订单------------"."<BR>";
                    $order_goods = db("splicingorder_goods")->where(['order_id'=>$value['id']])->select();
                    foreach($order_goods as $vals){
                        $vals['aux'] = json_decode($vals['aux'],true);
                        $content .= $value['posts_name']."<BR><R>".$value['posts_money']."</R>";
                        foreach($vals['aux'] as $v2){
                            $content .= $v2['name']."<BR><R>".$v2['price']."</R>";
                        }
                        $content .= "--------------------------------"."<BR>";
                    }
                    $content .= "<H><B>付款：".$value['money']."</B></H><BR>";
                    $content .= "-------------其他-------------"."<BR>";
                    if(date("H",$value['addtime']) < 12){
                        $addtime = date("d/m/Y H:i",$value['addtime']).'上午';
                    }else{
                        $addtime = date("d/m/Y H:i",$value['addtime']).'下午';
                    }
                    $content .= "<C>".$addtime."</C><BR>";

                    $content .= "<H><B><W>".$value['address']."</W></B></H><BR><BR>";
                    $content .= "<H><B><W>".$value['phone']."</W></B></H><BR><BR>";
                    $content .= "<H><B><W>".$value['name']."</W></B></H><BR>";
                    if(!empty($dayinji)){
                       $res = $this->post("printer/print", $this->makeRequestParams([
                            'sn' => $dayinji['sn'],
                            'content' => $content,
                            'times' => $times
                        ]));
                    }
 
                }
            }else{
                //未成团 - 查询订单
                $order_list = Splicingorder::where(['splicing_id'=>$v['id'],'order_status'=>'1'])->field("id,users_id,posts_name,order_sn,money,bonus_id,pay_type")->select();
                $order_list = collection($order_list)->toArray();
                foreach($order_list as $val){
                    if($val['pay_type'] == 1){
                        //微信支付
                        $wx     = new Wechatpay();
                        $cancel = $wx->refund($val['order_sn'], get_trade_no(),$val['money'],$val['money']); //支付单号
                        // dump($cancel);
                    }else{
                        //余额支付 返还余额
                        Users::where(['id'=>$val['users_id']])->setInc('money',$val['money']);
                        //生成余额记录
                        $log = [
                            'users_id'      =>      $val['users_id'],
                            'money'         =>      $val['money'],
                            'type'          =>      4,
                            'date'          =>      date("Y-m-d"),
                            'addtime'       =>      time(),
                            'desc'          =>      '拼单失败： '.$val['posts_name'],
                            'order_id'      =>      $val['id']
                        ];
                        UsersMoneylog::insert($log);
                    }
                }
                $order_ids = array_column($order_list,'id');
                Splicingorder::where(['id'=>['in',$order_ids]])->update(['order_status'=>'3']);
                Splicing::where(['id'=>$v['id']])->update(['status'=>'2']);
            }
        }
        echo '操作成功';
    }


    /**
     * 创建请求参数
     * @param array $params
     * @return array
     */
    public function makeRequestParams(array $params = [])
    {
        $params['appid'] = $this->appid;
        $params['timestamp'] = time();
        $params['sign'] = $this->makeSign($params);
        return $params;
    }

    /**
     * 创建签名
     * @param array $params
     * @return string
     */
    public function makeSign(array $params)
    {
        ksort($params);
        $sign = "";
        foreach ($params as $k => $v) {
            if ($k != "sign" && $k != "appsecret" && $v !== "" && !is_array($v) && !is_null($v)) {
                $sign .= $k . "=" . $v . "&";
            }
        }
        $sign = rtrim($sign, '&');
        $sign .= "&appsecret=" . $this->appsecret;

        return strtoupper(md5($sign));
    }

    /**
     * @param $method
     * @param $args
     * @return array
     * @throws Exception
     */
    public function __call($method, $args)
    {
        if (count($args) < 1) {
            throw new \InvalidArgumentException(
                'Magic request methods require a URI and optional options array'
            );
        }

        $method = strtoupper($method);
        $uri = $args[0];
        $params = isset($args[1]) ? $args[1] : [];
        return $this->_request($method, $uri, $params);
    }
    /**
     * @param string $method
     * @param string $uri
     * @param array $params
     * @return array
     * @throws Exception
     */
    protected function _request($method, $uri, array $params = [])
    {


        $ch = curl_init();
        $url = self::BASE_URI . $uri;
        if ($method == 'GET' || $method == 'DELETE') {
            $url .= '?' . http_build_query($params);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        }
        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CONNECTTIMEOUT);
//        curl_setopt($ch, CURLOPT_TIMEOUT, self::TIMEOUT);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $http_error = curl_error($ch);
        $http_errno = curl_errno($ch);
        curl_close($ch);

        $response = json_decode($response, 1);
        return $response;
    }
}